#ifndef QIPAN_H
#define QIPAN_H

#include <QWidget>
#include <QMouseEvent>
#include <QTimer>
#include "stdshared.h"

enum VerificationState {
    VERIFYING,
    VERIFIED,
    FAILED
};

class QiPan : public QWidget
{
    Q_OBJECT
public:
    explicit QiPan(QWidget *parent = nullptr);

    void resetGame();
    void regretMove();
    void setPlayerRole(ROLE role);
    void setAIDifficulty(int level) { m_aiLevel = level; }
    void setVerificationState(int x, int y, ROLE expectedRole);
    void handleVerificationResult(int x, int y, bool success);
    void triggerComputerMove();  

    bool isGameOver() const { return m_gameState != PLAYING; }
    GameState gameState() const { return m_gameState; }
    ROLE winner() const { return m_winner; }
    ROLE currentPlayer() const { return m_currentPlayer; }
    ROLE getExpectedRole() const { return m_expectedRole; }
    bool isPositionOccupied(int x, int y) const;
    void makeMove(int x, int y, ROLE role);
    void setCurrentPlayer(ROLE player);

private slots:
    void checkVerification();
    void computerMove();  
    
signals:
    void gameStatusChanged();
    void playerMoved(int x, int y);
    void computerMoved(int x, int y);
    void requestVerification(int x, int y, ROLE expectedRole);
    void piecesRemoved(const QList<QPair<ROLE, QPoint>>& pieces);
protected:
    void paintEvent(QPaintEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;
    void resizeEvent(QResizeEvent *event) override;

private:
    static const int BOARD_SIZE = 3;
    int m_cellSize;
    int m_margin;
    int m_marginLeft;
    int m_marginTop;

    ROLE m_chessboard[BOARD_SIZE][BOARD_SIZE];
    GameState m_gameState;
    ROLE m_winner;
    ROLE m_currentPlayer;
    ROLE m_playerRole;
    ROLE m_expectedRole;
    int m_hoverX;
    int m_hoverY;
    bool m_hoverFlag;
    bool isPlayerBlack() const {return m_playerRole == PLAYER;}
    int m_aiLevel;
    QTimer m_aiTimer;

    QList<QPoint> m_moveHistory;
    QList<ROLE> m_moveRoles;

    int m_verifyX;
    int m_verifyY;
    VerificationState m_verificationState;

    enum GameFlowState {
        PLAYER_TURN,
        WAITING_PLAYER_VERIFICATION,
        COMPUTER_TURN,
        WAITING_COMPUTER_VERIFICATION
    };
    
    GameFlowState m_gameFlowState;

    bool isCheckWin(int x, int y, ROLE role);
    bool isBoardFull();
    int minimax(int depth, bool isMax, int alpha, int beta);
    
    void checkGameState(int x, int y, ROLE role);

    void drawBoard(QPainter &painter);
    void drawPieces(QPainter &painter);
    void drawHover(QPainter &painter);
    void drawWinLine(QPainter &painter);
    void drawStatusText(QPainter &painter);

    QPoint findBestMove();
    QPoint findWinningMove(ROLE role);
    QPoint findRandomMove();

    QTimer m_verificationTimer;
};

#endif // QIPAN_H